import 'dart:io';

import 'package:flutter/foundation.dart';

import '../lib_baseview/utils/cache_util.dart';
import 'logger.dart';
// import 'package:get/get.dart';
// import 'package:lib_basemodel/server_client/base.pb.dart';
// import 'package:lib_basemodel/server_client/common/app.pb.dart';
// import 'package:lib_basemodel/server_client/user.pb.dart';
// import 'package:lib_basemodel/we_dart/lib_basechannels/proto/common_api.pb.dart';
// import 'package:lib_network/lib_network.dart';
// import 'package:lib_runtime/lib_runtime.dart';
// import 'package:path_provider/path_provider.dart';
// import 'package:lib_baseview/lib_baseview.dart';
// import 'package:package_info_plus/package_info_plus.dart';
// import 'package:lib_basechannels/pigeon_generate/common_api_impl.dart';
// import 'package:device_info_plus/device_info_plus.dart';
// import 'package:flutter_common/flutter_common.dart';

class GlobalConfig {
  // static GetSettingsResp? settingsResp;

  // static ConfResp? confResp;

  static bool hasEnterMainPage = false;
  static int timeEnterMain = 0;
  static bool appLifecycleActive = true;
  static int lastRecordTime = 0;

  static GlobalConfig? _ins;

  GlobalConfig._();

  static GlobalConfig get instance => _ins ??= GlobalConfig._();

  /// app统一的存储根目录
  late Directory appDirectory;

  /// debug开关
  static bool isDebug = false;
  static bool get hiddenAction {
    return false;
    // ///仅判断版本 不依赖用户登录
    // if(confResp == null){
    //   return true;
    // }else{
    //   if(confResp!.auditVersion){
    //     return true;
    //   }else{
    //     ///版本是正常 需要判断用户信息
    //     if(settingsResp == null){
    //       return false;
    //     }else{
    //       return settingsResp!.auditUser;
    //     }
    //   }
    // }
  }

  static bool get hiddenIosAction => hiddenAction && Platform.isIOS;
  static bool get hiddenAndroidAction => hiddenAction && Platform.isAndroid;

  static int bottomBarIndex = 0;

  ///默认正式环境  debug模式下 release默认正式 其他默认测试 可以切换
  static bool get isOfficial {
    int value = 0;
    if (GlobalConfig.isDebug) {
      value = CacheUtil.getInt(CacheKeys.serEnv, kReleaseMode ? 0 : 1);
    }
    return value == 0;
  }

  ///默认为空才请求 如需更新force传true
  static Future<bool> refreshSettings({bool force = false}) async {
    // if(settingsResp == null || force){
    //   var settingsResult = await AppApi.instance.getSettings();
    //   if(settingsResult.isSuccess){
    //     settingsResp = settingsResult.data;
    //   }
    //   return settingsResult.isSuccess;
    // }
    return true;
  }

  ///默认为空才请求 如需更新force传true
  static Future<bool> refreshConfInfo({bool force = false}) async {
    RLog.d('refreshConfInfo');
    // if(confResp == null || force){
    //   var result = await AppApi.instance.getConfInfo();
    //   RLog.d('refreshConfInfo${result.isSuccess}');
    //   if(result.isSuccess){
    //     confResp = result.data;
    //     JRNetwork.instance.useHttp2 = (confResp?.useHttp2??false);
    //     eventCenter.emit(Event(EventConstant.refreshConfInfo,data: confResp));
    //   }
    //   return result.isSuccess;
    // }
    return true;
  }

  static int timeDiff = 0;

  /// 服务时间
  static int get serverTime => DateTime.now().millisecondsSinceEpoch + timeDiff;

  ///请求头
  static Map<String, Object> commonParam = {};
  static bool hasInitCommonParam = false;

  Future init() async {
    /// 可用 打包命令 --dart-define=DEBUG_MODE=true 来控制
    const enableDebug = bool.fromEnvironment('DEBUG_MODE');
    assert(() {
      isDebug = true;
      return true;
    }());

    if (enableDebug) {
      isDebug = true;
    }

    // appDirectory = await getApplicationDocumentsDirectory();
  }

  String findProxy(Uri uri) {
    var ip = CacheUtil.get('ip');
    var port = CacheUtil.get('port');

    if (ip.isEmpty || port.isEmpty) {
      // 不设置代理
      return 'DIRECT';
    } else {
      return 'PROXY $ip:$port';
    }
  }

  static Future checkParam() async {
    if (commonParam["te_distinct_id"] == null ||
        (commonParam["te_distinct_id"] as String).isEmpty) {
      // commonParam["te_distinct_id"] = (await Reporter.getDistinctId())??"";
    }
  }

  static Future updateLanguage(String? languageCode) async {
    String code = 'en';
    if (languageCode == 'zh') {
      code = 'zh';
    } else if (languageCode == 'ar') {
      code = 'ar';
    }
    commonParam['accept_language'] = code;
  }

  static Future initCommonParam() async {
    if (hasInitCommonParam) {
      return;
    }
    // //调用原生iOS 获取cpu type
    // final info = await PackageInfo.fromPlatform();
    // commonParam["app_version"] = info.version;
    // commonParam["package_name"] = info.packageName;
    // commonParam["te_distinct_id"] = (await Reporter.getDistinctId())??"";
    // if (Platform.isAndroid) {
    //   FlutterCommon flutterCommon = FlutterCommon();
    //   var channel = await flutterCommon.getChannelId();
    //   var deviceId = await flutterCommon.getDeviceId();
    //   commonParam["channel"] = channel.isNotEmpty ? channel : channel;
    //   commonParam["cpu_type"] =
    //       (await CommonApi().getSupportedAbi(GetSupportedAbiReq())).data.abis;
    //   commonParam["platform"] = "android";
    //   AndroidDeviceInfo deviceData = (await DeviceInfoPlugin().androidInfo);
    //   commonParam["mac"] = deviceData.fingerprint;
    //   commonParam["device_model"] = deviceData.model ?? "";
    //   commonParam["device_id"] = deviceId;
    // } else if (Platform.isIOS) {
    //   /// 通过 MethodChannel 获取 iphone cpuType
    //   Map iosInfo = await FlutterCommon().iosDeviceInfo();
    //   commonParam["cpu_type"] = iosInfo["deviceCpuType"];
    //   commonParam["platform"] = "ios";
    //   commonParam["channel"] = "App Store";
    //   IosDeviceInfo deviceData = (await DeviceInfoPlugin().iosInfo);
    //   commonParam["mac"] = deviceData.identifierForVendor ?? "";
    //   commonParam["device_model"] = deviceData.model ?? "";
    //   commonParam["device_id"] = deviceData.identifierForVendor ?? "";
    // }
    // hasInitCommonParam = true;
    // // 设置埋点公共属性
    // Reporter.setSuperProperties({
    //   'channel': commonParam["channel"],
    //   'mac': commonParam["mac"],
    //   'deviceId': commonParam["deviceId"],
    //   'appVersion': commonParam["appVersion"]
    // });
    RLog.d('commonParam:$commonParam');
  }

  static logLastTimeDiff(String reason) {
    int lastTime = DateTime.now().millisecondsSinceEpoch;
    RLog.d('$reason : ${lastTime - lastRecordTime}', 'LastTimeDiff');
    lastRecordTime = lastTime;
  }
}
